package com.liuweiheng.cloud.controller;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
import com.liuweiheng.base.entity.R;
import com.liuweiheng.base.exception.UserException;
import com.liuweiheng.cloud.timer.*;
import org.quartz.DateBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 测试nacos配置中心数据获取
 * @author lwh
 * @since 2021/1/20
 */
@RestController
@RequestMapping("/")
@NacosPropertySource(dataId = "base2.yaml", autoRefreshed = true)
public class HomeController {

    @NacosValue(value="${server.name}", autoRefreshed = true)
    private String hello;

    @GetMapping("helloNacos")
    public R helloNacos() {
        return R.ok(hello);
    }

    @GetMapping("user")
    public R testException() throws UserException {
        throw new UserException(123, "123");
    }

    @GetMapping("/timer")
    public void testTimer() {
        TimerUtils.timer(new TimerTask() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "：" + new Date().getTime());
            }
        }, 1000, 1000);

    }

    /**
     * 执行Quartz定时任务，使用SimpleTrigger执行
     */
    @GetMapping("/quartz/simple/start")
    public void startQuartz() {
        Map<String, Object> jobDataMap = new HashMap<>();
///       ArrayList<Integer> list = new ArrayList<>();
///        list.add(1);
///        jobDataMap.put("count", list);
        JobEntity entity = new JobEntity();
        entity.setCount(1);
        jobDataMap.put("count", entity);
        QuartzManager.addJob(
                QuartParamBuilder.newQuartParam(MyJob.class)
                        .withTriggerKey("tName", "tGroup")
                        .withJobKey("jName", "jGroup")
                        .withJobDataMap(jobDataMap)
                        .withIntervalType("Seconds")
                        .withIntervalNum(3)
                        .withRepeatCount(10)
                        .buildSimple(), "skey", "svalue");
    }

    /**
     * 执行Quartz定时任务，使用CronTrigger执行
     */
    @GetMapping("/quartz/cron/start")
    public void stopQuartz() {
        Map<String, Object> jobDataMap = new HashMap<>();
        JobEntity entity = new JobEntity();
        entity.setCount(1);
        jobDataMap.put("count", entity);
        QuartzManager.addJob(
                QuartParamBuilder.newQuartParam(MyJob.class)
                        .withTriggerKey("tName2", "tGroup")
                        .withJobKey("jName2", "jGroup")
                        .withJobDataMap(jobDataMap)
                        .withCronDate("0/10 * * * * ?")
                        .withEndAt(DateBuilder.evenMinuteDateAfterNow())
                        .buildCron(), "skey", "svalue");
    }
}
